package com.zjun.demo.experimentaldemo.notification

import android.Manifest.permission.POST_NOTIFICATIONS
import android.R
import android.annotation.SuppressLint
import android.app.Notification
import android.app.Notification.VISIBILITY_PUBLIC
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Person
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Icon
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationCompat.DEFAULT_VIBRATE
import androidx.core.app.NotificationCompat.FLAG_SHOW_LIGHTS
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.IconCompat
import com.zjun.demo.experimentaldemo.MainActivity
import com.zjun.demo.experimentaldemo.base.BaseActivity
import com.zjun.demo.experimentaldemo.databinding.ActivityNotificationBinding
import java.lang.Thread.sleep
import java.util.UUID
import kotlin.concurrent.thread


/**
 * 通知
 */
class NotificationActivity : BaseActivity<ActivityNotificationBinding>() {

    override fun getLayoutId(): Int = com.zjun.demo.experimentaldemo.R.layout.activity_notification

    override fun initialize() {
        // 初始化默认通知渠道
    }

    /**
     * android13以上需要申请POST_NOTIFICATIONS
     */
    fun applyForNotificationPermission(view: View) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    ActivityCompat.requestPermissions(this, arrayOf(POST_NOTIFICATIONS), 1)
                }
            }
        } else {
            Toast.makeText(this, "android12以下无需权限", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 基础通知
     */
    fun notification(view: View) {
        checkHasNotifications {
            notifyMsg()
        }
    }

    /**
     * 全屏通知
     */
    fun fullScreenNotification(view: View) {

    }

    /**
     * 锁屏通知
     */
    @SuppressLint("MissingPermission")
    fun lockScreenNotification(view: View) {
        checkHasNotifications {
            val acceptIntent = PendingIntent.getActivity(
                this,
                0,
                Intent(this, MainActivity::class.java).apply {
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                },
                PendingIntent.FLAG_IMMUTABLE
            )
            val declineIntent = PendingIntent.getBroadcast(
                this,
                400,
                Intent("action.decline").setPackage(packageName),
                PendingIntent.FLAG_IMMUTABLE
            )
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                forIncomingCallNotificationGreaterThanOrEqualTo31(
                    channelID = CHANNEL_ID,
                    title = "title",
                    contentText = "contentText",
                    acceptIntent = acceptIntent,
                    declineIntent = declineIntent,
                    channelName = "channelName",
                    id = 15,
                    context = this
                )
            } else {
                forIncomingCallNotificationLessThan31(
                    channelID = CHANNEL_ID,
                    title = "title",
                    contentText = "contentText",
                    acceptIntent = acceptIntent,
                    declineIntent = declineIntent,
                    channelName = "channelName",
                    id = 15,
                    context = this
                )
            }
        }
    }

    @Suppress("DEPRECATION")
    @SuppressLint("NewApi", "MissingPermission")
    private fun forIncomingCallNotificationGreaterThanOrEqualTo31(
        channelID: String,
        title: String,
        contentText: String,
        acceptIntent: PendingIntent,
        declineIntent: PendingIntent,
        channelName: String,
        id: Int,
        context: Context,
        smallIcon: Int = com.zjun.demo.experimentaldemo.R.mipmap.ic_launcher,
    ) {
        val channelId = createNotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH, this)
        val builder = if (channelId != null) {
            Notification.Builder(context, channelId)
        } else {
            Notification.Builder(context)
        }
        val icon = Icon.createWithResource(this, com.zjun.demo.experimentaldemo.R.drawable.svg37)
        val caller = Person.Builder()
            .setIcon(icon)
            .setName(title)
            .setImportant(true)
            .build()
        val notificationStyle = Notification.CallStyle.forIncomingCall(caller, declineIntent, acceptIntent)
        val notification = builder
            .setSmallIcon(smallIcon)
            .setContentTitle(title)
            .setContentText(contentText)
            .setStyle(notificationStyle)
            .setContentIntent(acceptIntent)
            .setFullScreenIntent(acceptIntent, true)
            .setAutoCancel(true)
            .setOngoing(false)
            .setCategory(Notification.CATEGORY_CALL)
            .build()
        notification.visibility = VISIBILITY_PUBLIC
        val notificationManager = NotificationManagerCompat.from(this)
        notificationManager.notify(id, notification)
    }


    @Suppress("DEPRECATION")
    @SuppressLint("MissingPermission")
    private fun forIncomingCallNotificationLessThan31(
        channelID: String,
        title: String,
        contentText: String,
        acceptIntent: PendingIntent,
        declineIntent: PendingIntent,
        channelName: String,
        id: Int,
        context: Context,
        icon: Int = com.zjun.demo.experimentaldemo.R.mipmap.ic_launcher,
    ) {
        val channelId = createNotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH, this)
        val builder = if (channelId != null) {
            NotificationCompat.Builder(context, channelId)
        } else {
            NotificationCompat.Builder(context)
        }
        builder.setAutoCancel(true)
        val acceptAction = NotificationCompat.Action.Builder(
            // The icon that will be displayed on the button (or not, depends on the Android version)
            IconCompat.createWithResource(applicationContext, com.zjun.demo.experimentaldemo.R.mipmap.accept),
            // The text on the button
            getString(com.zjun.demo.experimentaldemo.R.string.accept_call),
            // The action itself, PendingIntent
            acceptIntent
        ).build()
        val declineAction = NotificationCompat.Action.Builder(
            // The icon that will be displayed on the button (or not, depends on the Android version)
            IconCompat.createWithResource(applicationContext, com.zjun.demo.experimentaldemo.R.mipmap.handup),
            // The text on the button
            getString(com.zjun.demo.experimentaldemo.R.string.decline_call),
            // The action itself, PendingIntent
            declineIntent
        ).build()
        val notification = builder
            .setContentTitle(title)
            .setContentText(contentText)
            .setAutoCancel(true)
            .setSmallIcon(icon)
            .addAction(declineAction)
            .addAction(acceptAction)
            .build()
        notification.visibility = VISIBILITY_PUBLIC
        val notificationManager = NotificationManagerCompat.from(this)
        notificationManager.notify(id, notification)
    }

    @SuppressLint("ObsoleteSdkInt")
    private fun createNotificationChannel(channelID: String, channelName: String, level: Int, context: Context): String? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel = NotificationChannel(channelID, channelName, level)
            manager.createNotificationChannel(channel)
            channelID
        } else {
            null
        }
    }

    /**
     * 锁屏通知
     */
    fun callNotification(view: View) {
        val INCOMING_CALL_CHANNEL_ID = "incoming_call"
        val notificationManager = NotificationManagerCompat.from(this)

    }

    /**
     * 发送广播
     */
    fun sendBroadcast(view: View) {
        val intent = Intent("action.accept")
        //在Android 8之后,发送广播务必显示设置接收的包名,否则广播无法正常接收到
        intent.setPackage(packageName)
        sendBroadcast(intent)
    }

    /**
     * 通知声音测试
     */
    fun notificationSound(view: View){
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            // 自定义声音文件（放在res/raw/目录下）
//            val soundUri = Uri.parse("android.resource://$packageName" + "/" + com.zjun.demo.experimentaldemo.R.raw.hazard_warning)
//
//            val audioAttributes = AudioAttributes.Builder()
//                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
//                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
//                .build()
//
//            val channel = NotificationChannel(
//                "your_channel_id",  // 必须与Builder使用的ID一致
//                "Channel Name",
//                NotificationManager.IMPORTANCE_DEFAULT
//            )
//            channel.setSound(soundUri, audioAttributes)
//            val notificationManager: NotificationManager = getSystemService(NotificationManager::class.java)
//            notificationManager.createNotificationChannel(channel)
//        }
//
//
//        val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, CHANNEL_ID)
//            .setSmallIcon(R.drawable.ic_delete)
//            .setContentTitle("通知标题")
//            .setContentText("通知内容")
        showNotificationWithSound()
    }

    @SuppressLint("MissingPermission")
    private fun showNotification(context: Context) {
        val soundUri = Uri.parse("android.resource://"+packageName + "/" + com.zjun.demo.experimentaldemo.R.raw.hazard_warning)

        val audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
            .build()

        val channel = NotificationChannel(
            "custom_sound_channel",
            "自定义声音通知",
            NotificationManager.IMPORTANCE_HIGH
        )

        channel.setSound(soundUri, audioAttributes)
        channel.description = "使用自定义声音的通知渠道"

        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)

        val builder: NotificationCompat.Builder = NotificationCompat.Builder(this, "custom_sound_channel")
            .setSmallIcon(com.zjun.demo.experimentaldemo.R.drawable.ic_launcher_round)
            .setContentTitle("新消息")
            .setContentText("您有一条新消息")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
    }

    var isSDF = false

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val soundUri = if(isSDF){
                Uri.parse("android.resource://"+packageName + "/" + com.zjun.demo.experimentaldemo.R.raw.hazard_warning)
            }else{
                Uri.parse("android.resource://"+packageName + "/" + com.zjun.demo.experimentaldemo.R.raw.video_request)
            }
            val channelId = if(isSDF){
                "custom_sound_channel"
            }else{
                "custom_sound_channel1"
            }
            val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build()

            val channel = NotificationChannel(
                channelId,
                "自定义声音通知",
                NotificationManager.IMPORTANCE_HIGH
            )

            channel.setSound(null, audioAttributes)
            channel.description = "使用自定义声音的通知渠道"

            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }

    var sdf = 0

    @SuppressLint("MissingPermission")
    fun showNotificationWithSound() {
        // 创建通知渠道（Android 8.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel()
        }

        // 构建通知
        val soundUri = Uri.parse("android.resource://"+packageName + "/" + com.zjun.demo.experimentaldemo.R.raw.hazard_warning)

        val channelId = if(isSDF){
            "custom_sound_channel"
        }else{
            "custom_sound_channel1"
        }

        val builder: NotificationCompat.Builder = NotificationCompat.Builder(
            this,
            channelId
        )
            .setSmallIcon(R.drawable.ic_delete)
            .setContentTitle("新消息")
            .setContentText("您有一条新消息$sdf")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setDefaults(DEFAULT_VIBRATE or FLAG_SHOW_LIGHTS )
        sdf++

        val notificationManager = NotificationManagerCompat.from(this)
        notificationManager.notify(1, builder.build())
    }

    /**
     * 需要android.permission.WAKE_LOCK静态权限
     */
    fun wakeUpScreen(view: View) {
        thread {
            sleep(3000)
            wakeUpScreen(this)
        }
    }

    private var requestCode = 0

    private fun notifyMsg() {

        val channelId = UUID.randomUUID().toString()
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val bundle = Bundle()
        bundle.putString("EXT", channelId)
        intent.putExtras(bundle)
        NotificationUtil.notify(
            context = this,
            channelID = "channelId",
            channelName = "my_channel_NAME",
            title = "通知",
            text = "收到一条消息",
            intent = intent,
            id = requestCode
        )
        requestCode ++
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i(TAG, "已关闭")
    }

    /**
     * 检查android13是否有通知权限
     */
    private fun checkHasNotifications(action: () -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(POST_NOTIFICATIONS), 1)
            } else {
                action.invoke()
            }
        } else {
            action.invoke()
        }
    }


    /**
     * 从息屏状态唤醒屏幕
     */
    private fun wakeUpScreen(context: Context) {
        val pm = context.getSystemService(POWER_SERVICE) as PowerManager
        val screenOn = pm.isInteractive
        if (!screenOn) {
            val wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CamVigil:mywakelocktag")
            // 点亮屏幕
            wl.acquire(15 * 1000L)
            // 释放
            wl.release()
        }
    }


    companion object {

        const val CHANNEL_ID = "ExperimentDemo"

        private const val TAG = "NotificationActivity"

    }

}